/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.ubc.icapture.genapha.actions;

import ca.ubc.icapture.genapha.beans.DataRequestApprovalDecorator;
import ca.ubc.icapture.genapha.beans.Login;
import ca.ubc.icapture.genapha.forms.DataRequestApprovalsForm;
import icapture.SQLMgr;
import icapture.beans.DB.DataRequestApproval;
import icapture.beans.DB.User;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author btripp
 */
public class DataRequestApprovalsAction extends Action
{

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
    {
        HttpSession session = request.getSession();
        if (Login.getLoggedIn(session))
        {
            User user = Login.getUser(session);
            if (user == null)
            {
                // User info is missing.
                // Something is broken. Relogin.
                return mapping.findForward("login");
            }

            ActionForward forward = new ActionForward();
            DataRequestApprovalsForm dataRequestAppForm = (DataRequestApprovalsForm) form;
            if (dataRequestAppForm.getSubmitType() == null || dataRequestAppForm.getSubmitType().isEmpty())
            {
                // Load data request approval list for this user
                List<DataRequestApprovalDecorator> dataReqAppList = new ArrayList<DataRequestApprovalDecorator>();
                for (DataRequestApproval dra : SQLMgr.getDataRequestApprovals(user))
                {
                    dataReqAppList.add(new DataRequestApprovalDecorator(dra));
                }
                dataRequestAppForm.setDataReqAppList(dataReqAppList);
                forward = mapping.findForward("success");
            }
            else if (dataRequestAppForm.getSubmitType().equalsIgnoreCase("Save"))
            {
                // Save comments and status to database.
                for (DataRequestApprovalDecorator dra : dataRequestAppForm.getDataReqAppList())
                {
                    SQLMgr.updateDataRequestApproval(dra);
                }
                forward = mapping.findForward("success");
            }
            else
            {
                // Something went wrong.
                forward = mapping.findForward("home");
            }
            return forward;
        }
        else
        {
            return mapping.findForward("login");
        }
    }
}
